package com.cedifie.lendapp.ui.steps.fm

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.cedifie.http.model.Progress
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.FmStepFaceBinding
import com.cedifie.lendapp.http.ApiService
import com.cedifie.lendapp.http.ApiService.addCommonParams
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.mvp.MvpFm
import com.cedifie.lendapp.ui.steps.act.CedCameraFaceAct
import com.cedifie.lendapp.ui.steps.act.CedStepAct
import com.cedifie.lendapp.ui.steps.impl.CedUploadPresenterImpl
import com.cedifie.lendapp.ui.steps.view.ICedUploadView
import com.cedifie.lendapp.utils.dialog.ReasonDialog
import com.cedifie.lendapp.utils.event.CedEventManager
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.helper.PermissionHelper
import com.cedifie.lendapp.utils.imagecovert.ImageConvert
import com.cedifie.lib_permission.OnPermissionCallback
import com.cedifie.lib_permission.Permission
import com.cedifie.lib_permission.XXPermissions
import com.lib.base.utils.ImageUtil
import com.lib.base.utils.log.LogHelper
import org.json.JSONObject
import java.io.File

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/21 16:40
 * @Annotation：人脸拍照
 */
class CedStepFaceFm: MvpFm<ICedUploadView, CedUploadPresenterImpl>(), ICedUploadView{

    private var _binding: FmStepFaceBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "binding is null"
    )

    //本地预览地址
    private var faceImgPath = ""
    //拍摄的头像地址
    private var faceImgUrl = ""

    override fun getCedRootView(inflater: LayoutInflater): View {
        _binding = FmStepFaceBinding.inflate(inflater)
        return binding.root
    }

    override fun initCedView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))
        showFaceBeforeView()
    }

    override fun initCedListener() {
        _binding?.imgView?.setOnClickListener {
            if (faceImgPath.isEmpty()){
                _binding?.btnStartOrSubmit?.callOnClick()
            }
        }

        //开始 、 提交
        _binding?.btnStartOrSubmit?.setOnClickListener {
            //开始人脸拍照
            if (faceImgUrl.isEmpty()){
                if (XXPermissions.isGranted(requireContext(), Permission.CAMERA)){
                    openCedCamera()
                } else {
                    val cameraItem = PermissionHelper.getCedCameraPermissionItem()
                    showCedCameraReasonDialog(cameraItem)
                }
                return@setOnClickListener
            }
            //提交
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_FACE_CONFIRM_SUBMIT,"")
            //立即上报
            CedEventManager.getInstance().updateCedEventsNow()

            val params = JSONObject().addCommonParams().apply {
                put("path", ApiService.API_PATH.CED_API_OCR_INFO_PATH)
                put("cardType","FACE")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
                put("faceImgUrl",faceImgUrl)//人脸图片
            }
            val act = context as CedStepAct
            act.onSubmitProcessAction(params)
        }

        //删除
        _binding?.imgRemove?.setOnClickListener {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_FACE_REMOVE_PHOTO,faceImgUrl)
            if (faceImgPath.isNotEmpty()){
                //删除图片
                val imgFile = File(faceImgPath)
                if (imgFile.isFile){
                    imgFile.delete()
                }
                faceImgPath = ""
            }
            faceImgUrl = ""
            showFaceBeforeView()
        }
    }

    override fun initCedData() {
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_STEP_FACE_START,"")
    }

    override fun createMvpPresenter(): CedUploadPresenterImpl {
        return CedUploadPresenterImpl(requireContext())
    }

    /**
     * 人脸拍照
     */
    private val faceCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                faceImgPath = result.data?.getStringExtra("imgLocalPath").toString()
                LogHelper.e(">>>>>>>>>face info ：$faceImgPath")
                showFaceAfterView()

                showCedLoading(isTOuchOut = false, isCancel = true,getString(R.string.loading))
                // 图片压缩处理
                ImageConvert.covert(requireContext(), file = File(faceImgPath)) { localPath, _ ->
                    if (localPath != null){
                        LogHelper.e("imageConvert success>>>>>>>$localPath")
                        mvpPresenter?.onCedUploadImageAction(localPath)
                    }
                }
            }
        }
    }

    /**
     * 显示未拍照View
     */
    private fun showFaceBeforeView(){
        _binding?.imgView?.setBorderWidth(0f)
        _binding?.imgView?.setImageResource(R.mipmap.icon_face_info_default_avater)
        _binding?.imgRemove?.visibility = View.INVISIBLE
        _binding?.btnStartOrSubmit?.text = getString(R.string.process_face_start)
    }

    /**
     * 显示拍照之后的View
     */
    private fun showFaceAfterView(){
        _binding?.let {
            it.imgView.setBorderWidth(8f)
            ImageUtil.instance?.loadImageUrl(requireContext(),it.imgView,faceImgPath)
            it.imgRemove.visibility = View.VISIBLE
            it.btnStartOrSubmit.text = getString(R.string.process_face_submit)
        }
    }

    /**
     * 打开相机
     */
    private fun openCedCamera(){
        HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_FACE_START_TAKE,"")
        faceCameraResultLauncher.launch(Intent(context,CedCameraFaceAct::class.java))
    }

    /**
     * 相机权限说明
     */
    private fun showCedCameraReasonDialog(item: JSONObject){
        val permission = item.optString("permission")
        val reasonDialog = ReasonDialog(context,permission,object: ReasonDialog.IDialogCallback{
            override fun onReasonDenyClick() {
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_PERMISSION_DENY,permission)
            }
            override fun onReasonAgreeClick() {
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_PERMISSION_AGREE,permission)
                requestCedCameraPermission(item)
            }
        })
        reasonDialog.setCancelable(true)
        reasonDialog.setCanceledOnTouchOutside(true)
        reasonDialog.show()
        reasonDialog.showCedPermissionItemViews(item)
    }

    /**
     * 授权
     */
    private fun requestCedCameraPermission(item: JSONObject){
        val permission = item.optString("permission")
        XXPermissions.with(requireContext())
            // 申请多个权限
            .permission(permission)
            .request(object: OnPermissionCallback {
                override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                    var permissionString = ""
                    p0.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                    openCedCamera()
                }
                override fun onDenied(p0: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    p0.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    XXPermissions.startPermissionActivity(requireContext(),permission)
                }
            })
    }

    /**
     * 上传进度
     */
    override fun showCedUploadProgress(totalSize: Long, currentSize: Long) {
    }

    /**
     * 上传成功
     */
    override fun showCedUploadSuccess(imgUrl: String) {
        faceImgUrl = imgUrl
        HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_FACE_USE_PHOTO, imgUrl)
    }

    /**
     * 上床失败
     */
    override fun showCedUploadFailed() {
        //上传失败，继续上传
        showCedLoading(isTOuchOut = false, isCancel = true,getString(R.string.loading))
        // 图片压缩处理
        ImageConvert.covert(requireContext(), file = File(faceImgPath)) { localPath, _ ->
            if (localPath != null){
                LogHelper.e("imageConvert success>>>>>>>$localPath")
                mvpPresenter?.onCedUploadImageAction(localPath)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_STEP_FACE_END,"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}